import scrollOpt from '../base/scrollOptimize'
import { UI_Listen, UI_Layer } from '../../config/ui_def'
import { WX_AD_CONFIG, Sdk_Platform, VIVO_AD_CONFIG, OPPO_AD_CONFIG, Ad_Type } from '../../frame/constants';
import util from '../tool/util'
cc.Class({
    extends: scrollOpt,

    properties: {
        itemSp: cc.Sprite,
        itemTitle: cc.Label,
        numLab: cc.Label,
        // skillLab: cc.Label,
        priceLab1: cc.Label,
        priceLab2: cc.Label,
        haveGet_node: cc.Node,
        timeLab: cc.Label,
        scrollView: cc.ScrollView,
        // priceLab2: cc.Label,
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start() {

    },

    // update (dt) {},

    initPage() {
        if (!he.pool.getPool('storeItem')) {
            he.pool.createPoolSync('storeItem', 5, cc.Prefab, 'uimod/storeItem')
        }
        switch (common.sdk_env) {
            case Sdk_Platform.OPPO:
                this.node.y = 50
                return
        }
    },

    updatePage() {
        let guideList = he.local.getJson('guideList', 'user')
        if (!guideList[6]) {
            this.scrollView.node.off(cc.Node.EventType.TOUCH_START, this.scrollView._onTouchBegan, this.scrollView, true);
            this.scrollView.node.off(cc.Node.EventType.TOUCH_MOVE, this.scrollView._onTouchMoved, this.scrollView, true);
            this.scrollView.node.off(cc.Node.EventType.TOUCH_END, this.scrollView._onTouchEnded, this.scrollView, true);
            this.scrollView.node.off(cc.Node.EventType.TOUCH_CANCEL, this.scrollView._onTouchCancelled, this.scrollView, true);
        }
        else {
            this.scrollView.node.on(cc.Node.EventType.TOUCH_START, this.scrollView._onTouchBegan, this.scrollView, true);
            this.scrollView.node.on(cc.Node.EventType.TOUCH_MOVE, this.scrollView._onTouchMoved, this.scrollView, true);
            this.scrollView.node.on(cc.Node.EventType.TOUCH_END, this.scrollView._onTouchEnded, this.scrollView, true);
            this.scrollView.node.on(cc.Node.EventType.TOUCH_CANCEL, this.scrollView._onTouchCancelled, this.scrollView, true);
        }
        gg.eventManager.on('shop', this.listenClient, this)
        let storlist = he.local.getJson('storeList')
        if (storlist && storlist.length > 0) {
            this.itemGroup = storlist
        } else {
            this.updateShop()
        }

        // this.updateShop()
        gg.eventManager.emit('main', { type: UI_Listen.MAIN_NEWPAGE, pageName: 'storePage' })
        this.shopInit()
        this.scheduleTime()
        this.getTime()
        this.adSwitch(true)
    },

    closeUI() {
        this.adSwitch(false)
        this.stopTimeSch()
        this.clearItem()
        gg.eventManager.emit('main', { type: UI_Listen.MAIN_NEWPAGE, pageName: 'BottomBar' })
    },
    adSwitch(status) {
        let guideList = he.local.getJson('guideList', 'user')
        if (!guideList[6]) {
            return
        }
        if (status) {
            switch (common.sdk_env) {
                case Sdk_Platform.OPPO:

                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'chayeAdFakeOPPO',
                        isShowAd: true,
                        isShowBanner: false,
                        adIndex: 9,
                        position: cc.Vec2(0, -650)
                    })
                    break
                case Sdk_Platform.HUAWEI:
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'hwAdPage',
                        cover: false,
                        isShowAd: true,
                        adType: Ad_Type.INSERT,
                        position: 0
                    })
                    break
            }
        }
        else {
            switch (common.sdk_env) {
                case Sdk_Platform.OPPO:
                    gg.uiManager.closePage(UI_Layer.Msg, 'chayeAdFakeOPPO')
                    break
                case Sdk_Platform.HUAWEI:
                    if (gg.uiManager.getPage(UI_Layer.Msg, 'hwAdPage')) {
                        gg.uiManager.closePage(UI_Layer.Msg, 'hwAdPage')
                    }
                    break
            }
        }
    },
    // adSwitch(status) {
    //     if (status) {
    //         switch (common.sdk_env) {
    //             case Sdk_Platform.WECHAT:
    //                 he.ad.getTdAdJson(WX_AD_CONFIG.tmIcon[3], this.creatAdIcon.bind(this))
    //                 break
    //         }
    //     } else {
    //         //  关掉广告
    //     }
    // },

    // creatAdIcon(config) {
    //     if (config.isOpen) {
    //         let pre = he.pool.getElement('adIcon')
    //         pre.position = cc.Vec2.ZERO
    //         pre.parent = this.node
    //         pre.opacity = 255
    //         let spt = pre.getComponent('adIcon')
    //         spt.init(config.creatives[0], false, true, 0.8)
    //     }
    // },


    listenClient(param) {
        switch (param.type) {
            case UI_Listen.SHOP_CLICK:
                if (this.itemGroup[param.index].isGet) {
                    gg.uiManager.addTip('已购买')
                } else {
                    gg.uiManager.addPage(UI_Layer.Cover, {
                        name: 'confirmPage',
                        cover: true,
                        info: this.itemGroup[param.index],
                        index: param.index
                    })
                }
                break

            case UI_Listen.SHOP_BUY:
                if (this.itemGroup[param.index].type != 3) {
                    gg.data.addItem(parseInt(this.itemGroup[param.index].id), parseInt(this.itemGroup[param.index].num))
                } else if (this.itemGroup[param.index].type == 3) {
                    let cardList = he.local.getJson('card', 'user')
                    // console.log(this.itemGroup[param.index])
                    for (let j = 0; j < parseInt(this.itemGroup[param.index].num); j++) {
                        cardList.push({ id: parseInt(this.itemGroup[param.index].icon), lv: parseInt(this.itemGroup[param.index].rarity) })
                    }
                    he.local.setJson('card', cardList, 'user')
                }
                let itemgrpCopy = util.copy(this.itemGroup)
                for (let i = 0; i < itemgrpCopy.length; i++) {
                    if (i == parseInt(param.index)) {
                        itemgrpCopy[i].isGet = true
                        break
                    }
                }

                for (let j = 0; j < itemgrpCopy.length; j++) {
                    if (itemgrpCopy[j].isAd) {
                        itemgrpCopy.splice(j, 1)
                        break
                    }
                }
                // this.itemGroup[param.index].isGet = true
                // console.log(itemgrpCopy)
                he.local.setJson('storeList', itemgrpCopy)
                this.itemGroup = itemgrpCopy
                this.shopInit()
                break
        }
    },

    shopInit() {
        this.clearItem()
        let haveShow = false
        // let adNum = this.randomNum(2, 4)
        // this.itemGroup.splice(adNum, 0, { isAd: true })
        for (let i = 0; i < this.itemGroup.length; i++) {
            if (i == 0) {
                this.itemTitle.string = `${this.itemGroup[i].name}`
                this.numLab.string = `x${this.itemGroup[i].num}`
                // this.skillLab.string = this.itemGroup[i].description
                this.priceLab1.string = parseInt(this.itemGroup[i].num) * this.itemGroup[i].diamond * parseInt(this.itemGroup[i].discount) / 10
                this.priceLab2.string = parseInt(this.itemGroup[i].num) * this.itemGroup[i].diamond
                // this.priceLab2.string = `${this.itemGroup[i].num * this.itemGroup[i].diamond}`
                if (this.itemGroup[i].type == 1) {
                    this.itemSp.spriteFrame = he.load.get('item', cc.SpriteAtlas, 'plist').getSpriteFrame(`${this.itemGroup[i].id}`)
                } else if (this.itemGroup[i].type == 3) {
                    this.itemSp.spriteFrame = he.load.get('skill', cc.SpriteAtlas, 'plist').getSpriteFrame(`${this.itemGroup[i].icon}`)
                }
                if (this.itemGroup[i].isGet) {
                    this.haveGet_node.active = true
                } else {
                    this.haveGet_node.active = false
                }
            } else {
                let pre = he.pool.getElement('storeItem')
                pre.parent = this.content
                let spt = pre.getComponent('storeItem')
                if (this.itemGroup[i].isAd && !haveShow) {
                    haveShow = true
                    if (spt) {
                        spt.initInfo(this.itemGroup[i], i, true)
                    }
                } else {
                    if (spt)
                        spt.initInfo(this.itemGroup[i], i, false)
                }
            }
        }
    },
    spClick() {
        gg.eventManager.emit('shop', { index: 0, type: UI_Listen.SHOP_CLICK })
    },

    clearItem() {
        for (let i = (this.content.children.length); i > 0; i--) {
            he.pool.putElement('storeItem', this.content.children[i - 1])
        }
    },

    updateShop() {
        let shopList = he.db.getTable('Shop')
        this.itemGroup = []
        this.discount = 0.6
        if (shopList && shopList.length > 0) {
            for (let i = 0; i < shopList.length; i++) {
                let itemGrp = shopList[i].monovalent.split('#')
                itemGrp = itemGrp[this.randomNum(0, itemGrp.length - 1)].split('_')
                let itemInfo = he.db.getDataByArgs('Item', { id: parseInt(itemGrp[0]) })
                if (itemInfo) {
                    itemInfo.num = itemGrp[1]
                }
                // itemInfo.sp = parseInt(shopList[i].type) == 1 ? true : false
                if (shopList[i].type == 1) {
                    itemInfo.sp = true
                    let countGrp = shopList[i].preferential.split('#')
                    this.discount = countGrp[this.randomNum(0, countGrp.length - 1)]
                    itemInfo.discount = this.discount
                } else {
                    itemInfo.sp = false
                }
                itemInfo.isGet = false
                this.itemGroup.push(itemInfo)
            }
        }
        he.local.setJson('storeList', this.itemGroup)
    },

    //范围内的随机数
    randomNum(minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    },


    closeServer() {
        this.uiBase.closePage()
        gg.eventManager.emit('main', { type: UI_Listen.MAIN_TOMAIN })
    },

    updateServer() {
        switch (common.sdk_env) {
            case Sdk_Platform.WECHAT:
                util.adFakeTip()
                he.ad.showVideo(() => {
                    this.updateShop()
                    this.shopInit()
                    this.adAdd()
                })
                break
            case Sdk_Platform.VIVO:

                he.local.click(`vivo_video_storePage`)

                he.ad.showVideo(() => {
                    this.updateShop()
                    this.shopInit()
                    this.adAdd()
                })

                break
            case Sdk_Platform.OPPO:
                he.ad.showVideo(OPPO_AD_CONFIG.videoId[4], () => {
                    this.updateShop()
                    this.shopInit()
                    this.adAdd()
                })
                break
            case Sdk_Platform.HUAWEI:
                he.ad.showVideo(() => {
                    this.updateShop()
                    this.shopInit()
                    this.adAdd()
                })
                break
            default:
                this.updateShop()
                this.shopInit()
                break
        }
    },

    adAdd() {
        let taskGrp = he.local.getJson('task', 'user')
        if (taskGrp && taskGrp.length > 0) {
            for (let j = 0; j < taskGrp.length; j++) {
                if (taskGrp[j].type == 9001) {
                    if (taskGrp[j].num < taskGrp[j].need) {
                        taskGrp[j].num += 1
                    }
                    break
                }
            }
        }
        he.local.setJson('task', taskGrp, 'user')
    },

    scheduleTime() {
        this.schedule(this.getTime, 1, 1440 * 60, 0)
    },

    stopTimeSch() {
        this.unschedule(this.getTime)
    },

    getTime() {
        let hour = new Date().getHours()
        let min = new Date().getMinutes()
        let miao = new Date().getSeconds()
        this.timeLab.string = `${util.prefixInteger((24 - hour - 1), 2)}:${util.prefixInteger((60 - min - 1), 2)}:${util.prefixInteger((60 - miao), 2)}`
    },

});
